package com.coder520.mamabike.security;

import com.coder520.mamabike.common.Parameter;
import com.coder520.mamabike.dao.cache.RedisDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;

/**
 * Created by ASUS on 2017/8/14.
 */
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private Parameter parameter;

    @Autowired
    private RedisDao redisDao;

    /**
     * 预认证处理过滤器
     * @return
     * @throws Exception
     */
    private MyPreAuthenticatedProcessingFilter getPreAuthenticatedProcessingFilter() throws Exception {
        MyPreAuthenticatedProcessingFilter myPreAuthenticatedProcessingFilter = new MyPreAuthenticatedProcessingFilter(parameter.getNoneSecurityPath(),redisDao);
        myPreAuthenticatedProcessingFilter.setAuthenticationManager(this.authenticationManager());
        return myPreAuthenticatedProcessingFilter;
    }

    @Override
    public void configure(WebSecurity web) throws Exception {
        web.ignoring().antMatchers(HttpMethod.OPTIONS,"/**");
    }

    @Override
    /**认证管理生成器*/
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.authenticationProvider(new MyAuthenticationProvider());
    }

    @Override
    /**
     * 安全认证配置
     */
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable()
                .authorizeRequests()
                /**无需认证的路径*/
                .antMatchers(parameter.getNoneSecurityPath().toArray(new String[parameter.getNoneSecurityPath().size()])).permitAll()
                .anyRequest().authenticated()
                .and()
                /**无状态的请求*/
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                .and()
                /**异常处理*/
                .httpBasic().authenticationEntryPoint(new MyAuthenticationEntryPoint())
                .and()
                /**过滤*/
                .addFilter(getPreAuthenticatedProcessingFilter())
        ;
    }
}
